package com.bilin.coin.widget;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.widget.TextView;

import com.bilin.coin.MainActivity;
import com.bilin.coin.R;
import com.bilin.coin.network.RequestUtils;
import com.bilin.coin.network.download.DownLoadListener;
import com.bilin.coin.network.download.ProgressResponseBody;
import com.bilin.coin.utils.FilePathUtils;
import com.bilin.coin.utils.MPermissionUtils;
import com.bilin.coin.utils.MobilePhoneDeviceInfo;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;


import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by LG on 2018/5/8.
 */

public class OngoingUpdateDialog extends Dialog {

    private TextView tvSpeed;
    private Context mContext;
    private Activity mActivity;
    private String strLink;

    public OngoingUpdateDialog(Context context) {
        super(context);
    }

    public OngoingUpdateDialog(Context context, int themeResId, String link) {

        super(context, themeResId);
        mContext=context;
        mActivity= (Activity) context;
        strLink=link;
        //strLink="https://gk-shop.oss-cn-hongkong.aliyuncs.com/app/android/test/app-37.apk";
    }

    protected OngoingUpdateDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
    }

   /* final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Integer progress = (Integer) msg.obj;
            if (progress < 90) {
                progress ++;
                msg.obj = progress;
                tvSpeed.setText(mContext.getString(R.string.download_already)+progress + "%");
                sendMsgMy(progress);
            } else {
                handler.removeMessages(10);
            }

        }
    };*/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ongoing_update_dialog);
        tvSpeed = findViewById(R.id.tv_speed);
        tvSpeed.setText(mContext.getString(R.string.download_already)+"0%");

        String permission[] = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        MPermissionUtils.requestPermissionsResult((Activity) mContext, new MPermissionUtils.OnPermissionListener() {
            @Override
            public void onPermissionGranted() {

                try {
                    //downloadFile();
                    downloadProgressTest();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onPermissionDenied() {
                MPermissionUtils.showTipsDialog(mContext);
            }
        },permission);
    }


    public void downloadFile(){
        //sendMsgMy(0);
        //strLink = "https://gk-shop.oss-cn-hongkong.aliyuncs.com/app/android/2.1.3/app.apk";
        RequestUtils
                .getFile()
                //.baseUrl("http://s.zhuishushenqi.com")
                .url(strLink)
                .downLoadFile(FilePathUtils.accessPath(mActivity, "downloadFile").getPath(), "Version"+ MobilePhoneDeviceInfo.getVersionName(mContext)+"BtBank.apk", new DownLoadListener() {
                    @Override
                    public void onStartDownload() {

                    }

                    @Override
                    public void onProgress(final int progress) {
                        mActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tvSpeed.setText(mContext.getString(R.string.download_already)+progress + "%");
                            }
                        });


                    }

                    @Override
                    public void onFinishDownload(File file) {
                        FilePathUtils.openFile(mContext,file);
                    }

                    @Override
                    public void onFail(String errorInfo) {

                    }
                });
    }

    private void downloadProgressTest() throws IOException {
        final String downloadFile = FilePathUtils.accessPath(mActivity, "downloadFile").getPath();
        //final String fileNme = "Version"+ MobilePhoneDeviceInfo.getVersionName(mContext)+ "mall1.apk";
        final String fileNme = "wc.apk";
        File file = new File(downloadFile,fileNme);
        //构建一个请求
        Request request = new Request.Builder()
                .url(strLink)
                .build();
        //构建我们的进度监听器
        final ProgressResponseBody.ProgressListener listener = new ProgressResponseBody.ProgressListener() {
            @Override
            public void update(long bytesRead, long contentLength, boolean done) {
                //计算百分比并更新ProgressBar
                final int percent = (int) (100 * bytesRead / contentLength);
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvSpeed.setText(mContext.getString(R.string.download_already)+percent + "%");
                        if (percent >= 100) {
                            dismiss();
                            FilePathUtils.openFile(mContext,file);
                        }
                    }
                });
                //Log.d("cylog","下载进度："+(100*bytesRead)/contentLength+"%");
            }
        };
        //创建一个OkHttpClient，并添加网络拦截器
        OkHttpClient client = new OkHttpClient.Builder()
                .addNetworkInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Response response = chain.proceed(chain.request());
                        //这里将ResponseBody包装成我们的ProgressResponseBody
                        return response.newBuilder()
                                .body(new ProgressResponseBody(response.body(),listener))
                                .build();
                    }
                })
                .build();
        //发送响应
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mActivity instanceof MainActivity) {
                            ((MainActivity)mActivity).showToast("请检查网络，稍后再试");
                        }
                    }
                });
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //从响应体读取字节流
                InputStream inputStream = response.body().byteStream();// 1
                //由于当前处于非UI线程，所以切换到UI线程显示图片
                saveFile(inputStream,downloadFile,fileNme );
            }
        });
    }

    /**
     * 保存文件
     *
     * @param inputStream
     * @throws IOException
     */
    public void saveFile(final InputStream inputStream, String strDestFileDir, String strDestFileName) throws IOException {

        InputStream is = null;
        byte[] buf = new byte[2048];
        int len = 0;
        FileOutputStream fos = null;
        try {
            is = inputStream;

            long sum = 0;

            File dir = new File(strDestFileDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(dir, strDestFileName);
            file.setReadable(true);
            file.setWritable(true);
            fos = new FileOutputStream(file);

            while ((len = is.read(buf)) != -1) {
                sum += len;
                fos.write(buf, 0, len);
                //final long finalSum = sum;
            }
            fos.flush();
            //Thread.sleep(10);



        } catch (FileNotFoundException e) {
            e.printStackTrace();
            dismiss();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
                if (is != null) is.close();
            } catch (IOException e) {
            }
            try {
                if (fos != null) fos.close();
            } catch (IOException e) {
            }

        }


    }


  /*  private void sendMsgMy(int progress) {
        Message msg = new Message();
        msg.obj = progress;
        msg.what = 10;
        if (progress < 30) {
            handler.sendMessageDelayed(msg,150);
        } else if (progress < 60) {
            handler.sendMessageDelayed(msg,100);
        } else {
            handler.sendMessageDelayed(msg,70);
        }
    }*/



}
